package com.coolw.test.compare;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Comparator:
 * 1.当前对象不需要实现Comparator接口，适用于灵活(即多种)排序的场景
 * 2.如果排序规则调整,通常不需要修改原来的代码,可新增排序类来支持新的排序规则
 *
 * @author coolw
 * @date 2024/6/4 19:55
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person1 {

    private String name;

    private int age;

    public static void main(String[] args) {
        Person1[] personArr = {
                new Person1("zhangsan", 20),
                new Person1("lisi", 25),
                new Person1("wangwu", 22)
        };

        // 排序前打印
        Arrays.stream(personArr).forEach(System.out::println);

        System.out.println("-------------------------------------");
        // 按名称升序
        Arrays.sort(personArr, new NameComparator());
        // 按年龄升序
        //Arrays.sort(personArr, new AgeComparator());

        // 排序后打印
        Arrays.stream(personArr).forEach(System.out::println);
    }

    /**
     * 按名字进行升序
     */
    static class NameComparator implements Comparator<Person1> {

        @Override
        public int compare(Person1 p1, Person1 p2) {
            return p1.getName().compareTo(p2.getName());
        }
    }

    /**
     * 按年龄进行升序
     */
    static class AgeComparator implements Comparator<Person1> {

        @Override
        public int compare(Person1 p1, Person1 p2) {
            return p1.getAge() - p2.getAge();
        }
    }
}
